const ModbusRTU = require("modbus-serial");
const net = require("net");
const Utils = require('./lib/util/Utils');
const modbusService = require('./service/modbusService');
const log4js = require('./lib/util/logConfig');
const logger = log4js.getLogger('oth');
logger.info('========== modbus slave ===========');

/*
* 初始化寄存器和线圈的值
* 每个数组有10000个元素，初始值分别为0（寄存器）或false（线圈）
*/
let holdingRegisters = new Array(10000).fill(0);
let inputRegisters = new Array(10000).fill(0);
let coils = new Array(10000).fill(false);
let discreteInputs = new Array(10000).fill(false);

/*
* 模拟从站的行为函数，包括获取和设置寄存器和线圈的值。
*/
const vector = {
    getInputRegister: function(addr, unitID) {
        console.log(`getInputRegister: address=${addr}, unitID=${unitID}`);
        return inputRegisters[addr];
    },
    getHoldingRegister: async function(addr, unitID) {
        //console.log(`getHoldingRegister: address=${addr}, unitID=${unitID}`);
        modbusService.setHoldingRegister(holdingRegisters);//设置值  引用传递
        return holdingRegisters[addr];
    },
    getCoil: function(addr, unitID) {
        console.log(`getCoil: address=${addr}, unitID=${unitID}`);
        return coils[addr];
    },
    getDiscreteInput: function(addr, unitID) {
        console.log(`getDiscreteInput: address=${addr}, unitID=${unitID}`);
        return discreteInputs[addr];
    },
    setRegister: function(addr, value, unitID) {
        console.log(`setRegister: address=${addr}, value=${value}, unitID=${unitID}`);
        holdingRegisters[addr] = value;
        return;
    },
    setCoil: function(addr, value, unitID) {
        console.log(`setCoil: address=${addr}, value=${value}, unitID=${unitID}`);
        coils[addr] = value;
        return;
    }
};

/*
* 创建TCP服务器
*/
const server = new net.Server();
server.listen(502, () => {
    console.log("Modbus TCP server is listening on port 502");
});

server.on("connection", (socket) => {
    console.log("New client connected");

    const serverTCP = new ModbusRTU.ServerTCP(vector, {
        host: "0.0.0.0",
        port: 502,
        debug: false,
        unitID: 255
    });

    socket.on("close", () => {
        console.log("Client disconnected");
    });

    socket.on("error", (err) => {
        console.error(`Socket error: ${err.message}`);
    });
});

server.on("error", (err) => {
    console.error(`Server error: ${err.message}`);
});
